package com.lhl.mq.mqServer;

import com.lhl.mq.common.*;
import com.lhl.mq.mqServer.core.BasicProperties;
import com.lhl.mq.mqServer.core.Message;

import javax.swing.text.StyledEditorKit;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 这个BrokerServer就为该消息队列的本体服务器
 * 本质上就是一个 TCP 的服务器
 */
public class BrokerServer {
    private ServerSocket serverSocket = null;

    //当前设置为一个 BrokerServer上只有一个虚拟主机
    private VirtualHost virtualHost = new VirtualHost("default");
    //使用这个哈希表表示当前所有的会话（也就是说当前有哪些客户端与我们的服务器进行通信）
    //key-channelId  value-Socket对象
    private ConcurrentHashMap<String, Socket> session = new ConcurrentHashMap<>();
    //引入一个线程池，来处理多个客户端的请求
    private ExecutorService executorService = null;
    //引入一个boolean变量来控制服务器是否继续运行
    private volatile boolean running = true;

    public BrokerServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("[BrokerServer] 启动!");
        executorService = Executors.newCachedThreadPool();

        try {
            while (running) {
                Socket clientSocket = serverSocket.accept();
                //把处理连接的逻辑丢给这个线程池
                executorService.submit(() -> {
                   processConnection(clientSocket);
                });
            }
        } catch (SocketException e) {
            System.out.println("[BrokeServer] 服务器停止运行！");
        }

    }

    //一般来说，停止服务器直接kill掉对应的进程就可以了
    //此处单独写一个停止方法，是为了后续的单元测试
    public void stop() throws IOException {
        running = false;
        //将线程池中的任务都放弃掉，让线程都销毁
        executorService.shutdownNow();
        serverSocket.close();
    }

    //通过这个方法，来处理一个客户端的连接
    //在这一个连接中，可能会涉及到多个请求和响应
    private void processConnection(Socket clientSocket) {
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            try (DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
                 DataInputStream dataInputStream = new DataInputStream(inputStream)) {
                while (true) {
                    //1、读取请求并解析
                    Request request = readRequest(dataInputStream);
                    //2、根据请求计算响应
                    Response response = process(request,clientSocket);
                    //3、将响应返回给客户端
                    writeResponse(dataOutputStream,response);
                }
            }
        }catch (EOFException | SocketException e){
                //DataInputStream 如果读到EOF，就会抛出一个EOFException异常
                //借用该异常来结束循环
                System.out.println("[BrokerServer] connection关闭，客户端地址：" + clientSocket.getInetAddress()
                           + clientSocket.getPort());
        }catch (IOException | ClassNotFoundException |MqException e) {
            System.out.println("[BrokerServer] connection 出现异常！");
            e.printStackTrace();
        }finally {
            try {
                //当连接处理完，需要关闭socket
                clientSocket.close();
                //一个TCP连接中会有多个chanel，需要把当前socket对应的所有的channel也全部清理掉
                clareClosedSession(clientSocket);
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



    private Request readRequest(DataInputStream dataInputStream) throws IOException {
        Request request = new Request();
        request.setType(dataInputStream.readInt());
        request.setLength(dataInputStream.readInt());
        byte[] payload = new byte[request.getLength()];
        int n = dataInputStream.read(payload);
        if (n != request.getLength()){
            throw new IOException("读取请求格式出错！");
        }
        request.setPayload(payload);
        return request;
    }

    private void writeResponse(DataOutputStream dataOutputStream, Response response) throws IOException {
        dataOutputStream.writeInt(response.getType());
        dataOutputStream.writeInt(response.getLength());
        dataOutputStream.write(response.getPayload());
        //刷新缓冲区
        dataOutputStream.flush();
    }

    private Response process(Request request, Socket clientSocket) throws IOException, ClassNotFoundException, MqException {
        //1、把request中的payload做一个初步的请求
        byte[] payload = request.getPayload();
        BasicArguments basicArguments = (BasicArguments) BinaryTool.fromBytes(payload);
        System.out.println("[Request] rid = " + basicArguments.getRid() + ", channel = " + basicArguments.getChannelId()
                    + ", type = " + request.getType() + ", length = " + request.getLength());
        //2、根据type的值来决定下一步要干什么
        int type = request.getType();
        boolean ok = true;

        if (type == 0x1){
            //创建channel
            session.put(basicArguments.getChannelId(),clientSocket);
            System.out.println("[BrokerServer] 成功创建channel，channel = " + basicArguments.getChannelId());
        }else if(type == 0x2){
            //关闭channel
            session.remove(basicArguments.getChannelId());
            System.out.println("[BrokerServer] 成功删除channel，channel = " + basicArguments.getChannelId());
        }else if(type == 0x3){
            //创建exchange
            ExchangeDeclareArguments arguments = (ExchangeDeclareArguments) BinaryTool.fromBytes(payload);
            ok = virtualHost.exchangeDeclare(arguments.getExchangeName(),arguments.getExchangeType(),arguments.isDurable(),
                    arguments.isAutoDelete(),arguments.getArguments());
        }else if(type == 0x4){
            //销毁exchange
            ExchangeDeleteArguments arguments = (ExchangeDeleteArguments) BinaryTool.fromBytes(payload);
            ok = virtualHost.exchangeDelete(arguments.getExchangeName());
        }else if(type == 0x5){
            //创建queue
            QueueDeclareArguments arguments = (QueueDeclareArguments) BinaryTool.fromBytes(payload);
            ok = virtualHost.queueDeclare(arguments.getQueueName(),arguments.isDurable(),arguments.isExclusive(),
                              arguments.isAutoDelete(),arguments.getArguments());
        }else if(type == 0x6){
            //销毁queue
            QueueDeleteArguments arguments = (QueueDeleteArguments) BinaryTool.fromBytes(payload);
            ok = virtualHost.queueDelete(arguments.getQueueName());
        }else if (type == 0x7){
            //创建binding
            QueueBindArguments arguments = (QueueBindArguments) BinaryTool.fromBytes(payload);
            ok = virtualHost.queueBind(arguments.getQueueName(),arguments.getExchangeName(),arguments.getBidingKey());
        }else if(type == 0x8){
            //销毁binding
            QueueUnBindArguments arguments = (QueueUnBindArguments) BinaryTool.fromBytes(payload);
            ok = virtualHost.queueUnBind(arguments.getExchangeName(),arguments.getQueueName());
        }else if (type == 0x9){
            //发送消息
            BasicPublishArguments arguments = (BasicPublishArguments) BinaryTool.fromBytes(payload);
            ok = virtualHost.basicPublish(arguments.getExchangeName(),arguments.getRoutingKey(),
                        arguments.getBasicProperties(),arguments.getBody());
        }else if(type == 0xa){
            //订阅消息
            BasicConsumeArguments arguments = (BasicConsumeArguments) BinaryTool.fromBytes(payload);
            ok = virtualHost.basicConsume(arguments.getConsumerTag(), arguments.getQueueName(), arguments.isAutoAck(), new Consumer() {
                @Override
                //这个回调函数要干的事情就是把服务器收到的消息发送给对应的订阅者
                public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws IOException, MqException, ClassNotFoundException {
                    //获取socket对象
                    //此处的consumerTag就相当于是channel
                    Socket socket = session.get(consumerTag);
                    if (socket == null || socket.isClosed()){
                        System.out.println("[BrokerServer] 订阅消息的客户端已关闭！");
                    }

                    //构造响应数据
                    SubScribeReturns subScribeReturns = new SubScribeReturns();
                    subScribeReturns.setRid("");
                    subScribeReturns.setChannelId(consumerTag);
                    subScribeReturns.setOk(true);
                    subScribeReturns.setBasicProperties(basicProperties);
                    subScribeReturns.setBody(body);
                    byte[] payload = BinaryTool.toBytes(subScribeReturns);
                    Response response = new Response();
                    //0xc表示服务器给客户端推送的消息
                    response.setType(0xc);
                    response.setLength(payload.length);
                    response.setPayload(payload);

                    //将数据写回给客户端
                    DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
                    writeResponse(dataOutputStream,response);
                }
            });
        } else if (type == 0xb) {
            //返回ack
            BasicAckArguments arguments = (BasicAckArguments) BinaryTool.fromBytes(payload);
            ok = virtualHost.basicAck(arguments.getQueueName(),arguments.getMessageId());
        }else {
            //type 非法
            throw new MqException("[BrokerServer] type非法，type = " + type);
        }
        //3、构造响应
        BasicReturns basicReturns = new BasicReturns();
        basicReturns.setOk(ok);
        basicReturns.setChannelId(basicArguments.getChannelId());
        basicReturns.setRid(basicArguments.getRid());

        Response response = new Response();
        byte[] returnPayload = BinaryTool.toBytes(basicReturns);
        response.setType(request.getType());
        response.setLength(returnPayload.length);
        response.setPayload(returnPayload);
        System.out.println("[Response] rid = " + basicArguments.getRid() + "channelId = " + basicArguments.getChannelId()
                + "type = " + response.getType() + "length = " + response.getLength());

        return response;
    }

   

    private void clareClosedSession(Socket clientSocket) {
        //遍历上述的session hash表，把要关闭的socket对应的键值对，统统删除掉
        List<String> list = new ArrayList<>();
        for (Map.Entry<String,Socket> entry: session.entrySet()){
            list.add(entry.getKey());
        }

        for (String channelId: list){
            session.remove(channelId);
        }
        System.out.println("[BrokerServer] 清理channel完毕，channelId = " + list);
    }


}
